package cn.smbms.controller;

import cn.smbms.pojo.Role;
import cn.smbms.pojo.User;
import cn.smbms.service.role.RoleService;
import cn.smbms.service.user.UserService;
import cn.smbms.tools.Constants;
import cn.smbms.tools.PageSupport;
import com.alibaba.fastjson.JSONArray;
import com.mysql.jdbc.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @program: smbms02
 * @description:
 * @author: wlg
 * @create: 2021-07-26 15:05:53
 **/
@Controller
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private RoleService roleService;

    @RequestMapping("/")
    public String login(){
        return "login";
    }

    @RequestMapping("/main.html")
    public String main(){
        return "frame";
    }


    @PostMapping("/dologin.html")
    public String doLogin(String userCode, String userPassword, HttpSession session, Model model){
        User user = userService.login(userCode,userPassword);
        if(null != user){//登录成功
            //放入session
            session.setAttribute(Constants.USER_SESSION, user);
            //页面跳转（frame.jsp）
            return "redirect:/main.html";
        }else{
            model.addAttribute("error", "用户名或密码不正确");
            return "login";
        }
    }

    @GetMapping("/logout")
    public String logout(HttpSession session){
        session.removeAttribute(Constants.USER_SESSION);
        return "redirect:/";
    }

    @RequestMapping("/user/userlist")
    public String userList(
            @RequestParam(value = "queryname",defaultValue = "") String queryUserName,
            @RequestParam(value = "queryUserRole",defaultValue = "0") Integer queryUserRole,
            @RequestParam(value = "pageIndex",defaultValue = "1") Integer currentPageNo,
            Model model){
        List<User> userList = null;
        //设置页面容量
        int pageSize = Constants.pageSize;
        //总数量（表）
        int totalCount	= userService.getUserCount(queryUserName,queryUserRole);
        //总页数
        PageSupport pages=new PageSupport();
        pages.setCurrentPageNo(currentPageNo);
        pages.setPageSize(pageSize);
        pages.setTotalCount(totalCount);

        int totalPageCount = pages.getTotalPageCount();

        //控制首页和尾页
        if(currentPageNo < 1){
            currentPageNo = 1;
        }else if(currentPageNo > totalPageCount){
            currentPageNo = totalPageCount;
        }


        userList = userService.getUserList(queryUserName,queryUserRole,currentPageNo, pageSize);
        model.addAttribute("userList", userList);
        List<Role> roleList = null;
        roleList = roleService.getRoleList();
        model.addAttribute("roleList", roleList);
        model.addAttribute("queryUserName", queryUserName);
        model.addAttribute("queryUserRole", queryUserRole);
        model.addAttribute("totalPageCount", totalPageCount);
        model.addAttribute("totalCount", totalCount);
        model.addAttribute("currentPageNo", currentPageNo);
        return "userlist";
    }


    @GetMapping("/user/modifypwd")
    public String modifyPwd(){
        return "pwdmodify";
    }

    @GetMapping("/user/getpwd")
    @ResponseBody//返回纯数据，不走视图解析器了
    public String oldPwdIsTrue(HttpSession session,String oldpassword){
        Object o = session.getAttribute(Constants.USER_SESSION);
        Map<String, String> resultMap = new HashMap<String, String>();

        if(null == o ){//session过期
            resultMap.put("result", "sessionerror");
        }else if(StringUtils.isNullOrEmpty(oldpassword)){//旧密码输入为空
            resultMap.put("result", "error");
        }else{
            String sessionPwd = ((User)o).getUserPassword();
            if(oldpassword.equals(sessionPwd)){
                resultMap.put("result", "true");
            }else{//旧密码输入不正确
                resultMap.put("result", "false");
            }
        }
        return JSONArray.toJSONString(resultMap);
    }


    @PostMapping("/user/savepwd")
    public String savePwd(HttpSession session,String newpassword,Model model) throws Exception {
        Object o = session.getAttribute(Constants.USER_SESSION);
        boolean flag = false;
        if(o != null && !StringUtils.isNullOrEmpty(newpassword)){
            flag = userService.updatePwd(((User)o).getId(),newpassword);
            if(flag){
                model.addAttribute(Constants.SYS_MESSAGE, "修改密码成功,请退出并使用新密码重新登录！");
                session.removeAttribute(Constants.USER_SESSION);//session注销
            }else{
                model.addAttribute(Constants.SYS_MESSAGE, "修改密码失败！");
            }
        }else{
            model.addAttribute(Constants.SYS_MESSAGE, "修改密码失败！");
        }
        return "pwdmodify";
    }

   /* @GetMapping("/user/view/{uid}")//REST风格
    public String viewUser(@PathVariable(value = "uid") String id,Model model){
        if(!StringUtils.isNullOrEmpty(id)){
            //调用后台方法得到user对象
            User user = userService.getUserById(id);
            model.addAttribute("user", user);
            return "userview";
        }else{
            return "error";
        }
    }*/

    @GetMapping(value = "/user/view/{uid}"/*,produces = {"application/json;charset=utf-8"}*/)//REST风格
    @ResponseBody
    public String viewUser(@PathVariable(value = "uid") String id) throws Exception {
        if(!StringUtils.isNullOrEmpty(id)){
            //调用后台方法得到user对象
            User user = userService.getUserById(id);
            return JSONArray.toJSONString(user);
        }else{
            return "error";
        }
    }

    @GetMapping("/user/modify")
    public String toModify(@RequestParam(value = "uid") String id,Model model) throws Exception {
        if(!StringUtils.isNullOrEmpty(id)){
            //调用后台方法得到user对象
            User user = userService.getUserById(id);
            model.addAttribute("user", user);
            return "usermodify";
        }else{
            return "error";
        }
    }


    @GetMapping("/user/rolelist")
    @ResponseBody
    public String getRoleList(){
        List<Role> roleList = null;
        roleList = roleService.getRoleList();
        //把roleList转换成json对象输出
       return JSONArray.toJSONString(roleList);
    }

    @PostMapping("/user/doModify")
    public String doModify(User user,HttpSession session) throws Exception {
        user.setModifyBy(((User)session.getAttribute(Constants.USER_SESSION)).getId());
        user.setModifyDate(new Date());

        if(userService.modify(user)){
           return "redirect:/user/userlist";
        }else{
            return "usermodify";
        }
    }

    @GetMapping("/user/delete")
    @ResponseBody
    public String delete(@RequestParam(value = "uid",defaultValue = "0") Integer delId) throws Exception {

        HashMap<String, String> resultMap = new HashMap<String, String>();
        if(delId <= 0){
            resultMap.put("delResult", "notexist");
        }else{
            if(userService.deleteUserById(delId)){
                resultMap.put("delResult", "true");
            }else{
                resultMap.put("delResult", "false");
            }
        }
        return JSONArray.toJSONString(resultMap);
    }

    @GetMapping("/user/toadd")
    public String toAdd(){
        return "useradd";
    }

    @PostMapping("/user/doadd")
    public String doAdd(User user,HttpSession session){
        user.setCreationDate(new Date());
        user.setCreatedBy(((User)session.getAttribute(Constants.USER_SESSION)).getId());

        if(userService.add(user)){
            return "redirect:/user/userlist";
        }else{
            return "useradd";
        }
    }

    @GetMapping("/user/ucexist")
    @ResponseBody
    public String userCodeExist(String userCode){

        HashMap<String, String> resultMap = new HashMap<String, String>();
        if(StringUtils.isNullOrEmpty(userCode)){
            //userCode == null || userCode.equals("")
            resultMap.put("userCode", "exist");
        }else{
            User user = userService.selectUserCodeExist(userCode);
            if(null != user){
                resultMap.put("userCode","exist");
            }else{
                resultMap.put("userCode", "notexist");
            }
        }
        return JSONArray.toJSONString(resultMap);
    }

    /*@ExceptionHandler
    public String handleException(Exception e,Model model){
        model.addAttribute("e",e);
        return "error";
    }*/

}
